package fr.univ.context.data.handler;

import fr.univ.context.utilities.Constants;

import android.content.Context;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;

public class AbstractInfoTable {

	// Helper object to create, open, and/or manage a database. 
	private CustomSqliteOpener customSqliteOpener;
    
	// Database object
	private SQLiteDatabase database;
    
    private String tableName;
    private String scriptCreateTable;
    private String[] columns;
    
    public AbstractInfoTable(Context context, String tableName, String scriptCreateTable, String[] columns) {
    	
    	this.tableName = tableName;
    	this.scriptCreateTable = scriptCreateTable;
    	this.columns = columns;
    	
		/*Create a helper object to create, open, and/or manage a database. 
		 * The database is not actually created or opened until one of 
		 * getWritableDatabase() or getReadableDatabase() is called.*/
    	customSqliteOpener = new CustomSqliteOpener(context);
    	
    	open();
    }
    
    // Called when the database has been opened.
    public void open() throws SQLException {
    	database = customSqliteOpener.getWritableDatabase();
    }
    
    // Close the database object.
    public void close() {
        customSqliteOpener.close();
    }
    
    public SQLiteDatabase getDatabase() {
        return database;
    }
    
    public String getTableName(){
    	return tableName;
    } 
    
    public String getScriptCreateTable(){
    	return scriptCreateTable;
    }
    
    public String[] getColumns(){
    	return columns;
    }

    // A helper class to manage database creation and version management.
	private class CustomSqliteOpener extends SQLiteOpenHelper {
        
    	public CustomSqliteOpener(Context context) {
            super(context, Constants.DATABASE_NAME, null, Constants.DATABASE_VERSION);
        }

		@Override
		//Called when the database is created for the first time.
        public void onCreate(SQLiteDatabase database) {
            database.execSQL(getScriptCreateTable());
        }
		
		@Override
		//Called when the database has been opened.
		public void onOpen(SQLiteDatabase database) {
		    database.execSQL(getScriptCreateTable());
		}

		@Override
		//Called when the database needs to be upgraded.
        public void onUpgrade(SQLiteDatabase database, int arg1, int arg2) {
            database.execSQL("DROP TABLE IF EXISTS " + getTableName());
            onCreate(database);
        }
    }
}